<template>
	<view class="content" :class="typecss()" v-if="this.go_error==false">
		<!-- 页面自定义标题 -->
		<!-- <view class="header"> -->
		<!-- <image class="img1" src="/static/back.png" mode=""></image>
			<view class="title">智能情景护眼落地灯</view>
			<image class="img2" src="/static/switch.png" mode="" @click="open_light()"></image>
			<image class="img3" src="/static/more.png" mode=""></image> -->
		<!-- </view> -->

		<!-- 设备开关机 -->
		<!-- <view class="logo">
			<image class="img" src="/static/logo.png" mode="" @click="open_light()"></image>
			<span class="sp" v-if="this.switch_type">设备启动</span>
			<span class="sp" v-else>设备关闭</span>
		</view> -->

		<view class="device">
			<view class="left" v-if="this.switch_type">
				<span class="sp1">智能情景护眼落地灯</span>
				<span class="sp2" v-if="this.error_show">离线</span>
				<span class="sp2" v-else>已开启</span>
				<image @click="open_light()" v-if="this.error_show" class="img" src="/static/close.png" mode=""></image>
				<image @click="open_light()" v-else class="img" src="/static/close_act.png" mode=""></image>
			</view>
			<view class="left" v-else>
				<span class="sp1">智能情景护眼落地灯</span>
				<span class="sp2" v-if="this.error_show">离线</span>
				<span class="sp2" v-else>已关闭</span>
				
				<image @click="open_light()" class="img" src="/static/close.png" mode=""></image>
			</view>

			<view class="right">
				<image class="img" src="/static/device.png" mode=""></image>
			</view>
		</view>
		<view class="error_box" v-if="this.error_show">
			<span class="sp1">设备已离线</span>
			<span class="sp2">请保持设备通电联网</span>
			<button class="bt" @click="error_bt">了解更多</button>
		</view>

		<!-- 光源调节 -->
		<view class="lightsource">
			<view class="lightsource_top">
				<view class="left">上光源</view>
				<view class="right" v-if="this.error_show||this.switch_type==false">
					<slider disabled=true :value="lightsource_top" @change="change('top', $event, 'common')" min="0" max="100" block-size="16" backgroundColor="#E6E6E6" activeColor="#3084F2" />
				</view>
				<view class="right" v-else>
					<slider :value="lightsource_top" @change="change('top', $event, 'common')" min="0" max="100" block-size="16" backgroundColor="#E6E6E6" activeColor="#3084F2" />
				</view>
			</view>
			<view class="lightsource_bottom">
				<view class="left">下光源</view>
				<view class="right" v-if="this.error_show||this.switch_type==false">
					<slider
					    disabled=true
						:value="lightsource_bottom"
						@change="change('bottom', $event, 'common')"
						min="0"
						max="100"
						block-size="16"
						backgroundColor="#E6E6E6"
						activeColor="#3084F2"
					/>
				</view>
				<view class="right" v-else>
					<slider
						:value="lightsource_bottom"
						@change="change('bottom', $event, 'common')"
						min="0"
						max="100"
						block-size="16"
						backgroundColor="#E6E6E6"
						activeColor="#3084F2"
					/>
				</view>
			</view>
		</view>

		<!-- 我的模式 -->
		<!-- 	<view class="Mode">
			<p>我的模式</p>
			<view class="Mode_info">
				<view class="box" v-for="(item, index) in List" :key="index">
					<view class="" v-if="item.mode == true" @click="changeBox(index)">
						<image class="img" :src="item.active ? '/static/mode1.png' : '/static/mode2.png'" mode=""></image>
						<image class="img" :src="item.img" mode=""></image>
						<span class="sp" :style="{ color: item.active ? '#00d8af' : '#7F7F7F' }">{{ item.title }}</span>
					</view>
					<view class="" v-else @click="open_addMode(item)">
						<image class="img" src="/static/mode3.png" mode=""></image>
						<span class="sp">{{ item.title }}</span>
					</view>
				</view>
			</view>
		</view> -->

		<!-- 情景模式 -->
		<view class="Scene_Mode">
			<p>情景模式</p>
			<view class="Scene_Mode_info" style="pointer-events: none" v-if="this.error_show||this.switch_type==false">
				<view class="box" v-for="(item, index) in List_Scene" :key="index">
					<view class="" @click="changeBox_Scene(index)">
						<image class="img" :src="`../../static/${item.active ? item.img_act : item.img}`" mode=""></image>
						<span class="sp" :style="{ color: item.active ? '#3084F2' : '#7F7F7F' }">{{ item.title }}</span>
					</view>
				</view>
			</view> 
			<view class="Scene_Mode_info" v-else>
				<view class="box" v-for="(item, index) in List_Scene" :key="index">
					<view class="" @click="changeBox_Scene(index)">
						<image class="img" :src="`../../static/${item.active ? item.img_act : item.img}`" mode=""></image>
						<span class="sp" :style="{ color: item.active ? '#3084F2' : '#7F7F7F' }">{{ item.title }}</span>
					</view>
				</view>
			</view>
		</view>

		<!-- 延时模式 -->
		<!-- 		<view class="Delay">
			<image class="img" src="/static/Delay.png" mode=""></image>
			<span class="sp1" v-if="this.switch_type">延时关闭</span>
			<span class="sp1" v-else>延时开启</span>
			<switch class="switch" color="#00d8af" :checked="checked" @change="switchChange" />
			<span class="sp2">延时时间</span>
			<span class="Delay_exit">{{ Delaytime }}分钟</span>
			<span class="Delay_exit" style="right: 16px;">></span>
			<image class="Delay_exit" @click="this.$refs.popup_time.open('bottom')" style="right: 16px; width: 16px; height: 16px" src="/static/right.png" mode=""></image>
			<span class="sp3">剩余时间</span>
			<span class="Delay_exit" style="top: 131px">{{ remainder }}分钟</span>
		</view> -->

		<!-- 定时模式 -->
		<!-- 	<view class="timing" @click="Go_timing">
			<image class="img" src="/static/timing.png" mode=""></image>
			<span class="sp1">定时开关</span>
			<image class="right" src="/static/right.png" mode=""></image>
		</view> -->

		<!-- 智能场景 -->
		<!-- 	<view class="timing">
			<image class="img" src="/static/AI.png" mode=""></image>
			<span class="sp1">智能场景</span>
			<image class="right" src="/static/right.png" mode=""></image>
		</view> -->

		<!-- 我的模式add弹窗 -->
		<!-- 遮罩层 -->
		<!-- <view v-if="this.popup == true" class="overlay"></view> -->
		<!-- 
		<view class="popup" v-if="this.popup == true">
			<view class="popup_header">
				<p>模式设置</p>
			</view>
			<view class="info">
				<view class="lightsource_top">
					<view class="left">上光源</view>
					<view class="right">
						<sliderBar Width="193" max="100" min="0" @change="change('top', $event, 'Mymod')"></sliderBar>
					</view>
				</view>
				<view class="lightsource_bottom">
					<view class="left">下光源</view>
					<view class="right">
						<sliderBar Width="193" max="100" min="0" @change="change('bottom', $event, 'Mymod')"></sliderBar>
					</view>
				</view>
			</view>
			<view class="bt">
				<button class="button gery" @click="this.popup = false">取消</button>
				<button class="button green" @click="add_Mode">确定</button>
			</view>
		</view> -->

		<!-- 延时设置 -->
		<uni-popup ref="popup_time">
			<view class="popup_time">
				<TimePicker usekey="timeSelect" title="延迟设置" @change="bindChange" @close="closepopup_time" />
			</view>
		</uni-popup>

		<!-- 提示 -->
		<showTip ref="showtip" :title="tiptitle" :type="modeltype"></showTip>
	</view>
	
	<view class="content2" v-if="this.go_error==true" >
		<view class="header">
			<p>如何使设备上线？</p>
		</view>
		<view class="info">
			<p>1.确认电源处于接通状态或重启设备。</p>
			<p>2.可以长按预约按键5秒以上，重新配网。</p>
			<p>3.如仍有疑问，请拨打021-52551258联系客服人员为您 解答。</p>
		</view>
		<button class="bt" @click="this.go_error=false">我知道了</button>
	</view>
</template>

<script>
import sliderBar from '@/componts/sliderBar/sliderBar.vue';
import showTip from '@/componts/showmodel/showmodel.vue';
import TimePicker from '@/componts/TimePicker/TimePicker.vue';
const currentTime = new Date().toLocaleString();
export default {
	components: {
		sliderBar,
		showTip,
		TimePicker // 注册组件
	},
	data() {
		return {
			popup: false,
			checked: false, //延迟开关
			title: '',
			lightsource_top: 0,
			lightsource_bottom: 0,
			text: 0,
			error_show: false,
			List: [
				{
					id: 1,
					mode: true,
					active: false,
					title: '自定模式1'
				},
				{ id: 2, mode: true, active: false, title: '自定模式2' },
				{ id: 3, mode: false, active: false, title: '自定模式3' },
				{ id: 4, mode: false, active: false, title: '自定模式4' }
			],
			List_Scene: [
				{
					active: false,
					title: '日光',
					img_act: 'son_act.png',
					img: 'son.png',
					upperBrightness: '100',
					lowerBrightness: '100',
					id: '01'
				},
				{
					active: false,
					title: '月光',
					img_act: 'moon_act.png',
					img: 'moon.png',
					upperBrightness: '5',
					lowerBrightness: '0',
					id: '02'
				},
				{
					active: false,
					title: '温馨',
					img_act: 'warm_act.png',
					img: 'warm.png',
					upperBrightness: '5',
					lowerBrightness: '35',
					id: '03'
				},
				{
					active: false,
					title: '影院',
					img_act: 'cinema_act.png',
					img: 'cinema.png',
					upperBrightness: '50',
					lowerBrightness: '10',
					id: '04'
				},
				{
					active: false,
					title: '阅读',
					img_act: 'read_act.png',
					img: 'read.png',
					upperBrightness: '85',
					lowerBrightness: '85',
					id: '05'
				},
				{
					active: false,
					title: '电脑',
					img_act: 'Computer_act.png',
					img: 'Computer.png',
					upperBrightness: '60',
					lowerBrightness: '25',
					id: '06'
				},
				// {
				// 	active: false,
				// 	title: '助眠',
				// 	img_act: 'Sleep_aids_act.png',
				// 	img: 'Sleep_aids.png',
				// 	upperBrightness: '60',
				// 	lowerBrightness: '60',
				// 	id: '07'
				// },
				// {
				// 	active: false,
				// 	title: '唤醒',
				// 	img_act: 'weekup_act.png',
				// 	img: 'weekup.png',
				// 	upperBrightness: '1',
				// 	lowerBrightness: '1',
				// 	id: '08'
				// },
				{
					active: false,
					title: '',
					img_act: '',
					img: '',
					upperBrightness: '60',
					lowerBrightness: '60',
					id: ''
				},
				{
					active: false,
					title: '',
					img_act: '',
					img: '',
					upperBrightness: '',
					lowerBrightness: '',
					id: ''
				}
			],
			Delaytime: 5,
			DelayList: {},
			remainder: 0,
			tiptitle: '',
			modeltype: '',
			time: '',
			currentUrl: '',
			deviceId: '', //当前deviceId
			switch_type: false, //大路灯开关
			Mymod: '',
			Mymod_toplight: '',
			Mymod_bottomlight: '',
			cron: '', //core表达式
			Delayswitch: '',
			go_error:false
		};
	},
	onLoad() {
		// Hejia.ready(function () {
		// 	// 页面加载完成后要立即调用Hejia全局对象执行的代码逻辑写这里
		// 	console.log('执行getUrlParam获取deviceID:');
		// 	// Hejia.getUrlParam(this.currentUrl, 'deviceId');
		// 	Hejia.onMessage(function (obj) {
		// 		console.log('接收到服务器消息', obj[0]);
		// 		if (obj[0].type == 3) {
		// 			that.error_show = false;
		// 		} else if (obj[0].type == 4) {
		// 			that.error_show = true;
		// 		} else if (obj[0].type == 6) {
		// 			that.deviceId = obj[0].deviceId;
		// 			// 打印 deviceId 的值
		// 			console.log('deviceId:', that.deviceId);
		// 			that.getDeviceInfo(that.deviceId);
		// 		}
		// 	});
		// });
		let that = this
		setTimeout(function () {
		    Hejia.ready(function () {
				that.GetUrl();
		        Hejia.onMessage(function (obj) {
		            console.log('接收到服务器消息', obj[0]);
		            if (obj[0].type == 3) {
		                that.error_show = false;
		            } else if (obj[0].type == 4) {
		                that.error_show = true;
		            } else if (obj[0].type == 6) {
		                that.deviceId = obj[0].deviceId;
		                console.log('deviceId:', that.deviceId);
		                that.getDeviceInfo(that.deviceId);
		            }
		        });
		    });
		}, 2000);
		// this.cron = this.generateCronExpression(0, 5);
		// console.log('当前core表达式为:', this.cron);
	},
	methods: {
		typecss() {
			let classList = [];
			// 根据 switch_type 的值决定使用 class1 或 class2
			classList.push(this.switch_type ? 'color1' : 'color2');
			// 如果 error_show 为 true，则添加 class3
			if (this.error_show) {
				classList = [];
				classList.push('color3');
			}
			return classList;
		},
		change(lightType, newValue, settings) {
			console.log('测试', newValue);
			// 初始化定时器对象（如果不存在）
			if (!this.timers) {
				this.timers = {};
			}

			// 清除对应 lightType 的旧定时器
			if (this.timers[lightType]) {
				clearTimeout(this.timers[lightType]);
			}

			// 为当前 lightType 设置新定时器
			this.timers[lightType] = setTimeout(async () => {
				// 注意这里改为 async
				if (settings === 'common') {
					if (lightType === 'top') {
						this.lightsource_top = newValue.detail.value.toString();
						console.log('上光源:', this.lightsource_top);
						await this.setControlParam('upperBrightness', this.lightsource_top); // 使用 await
					} else if (lightType === 'bottom') {
						this.lightsource_bottom = newValue.detail.value.toString();
						console.log('下光源:', this.lightsource_bottom);
						await this.setControlParam('lowerBrightness', this.lightsource_bottom);
					}
				} else if (settings === 'Mymod') {
					if (lightType === 'top') {
						this.Mymod_toplight = newValue.detail.value.toString();
						console.log('Mymod上光源:', this.Mymod_toplight);
					} else if (lightType === 'bottom') {
						this.Mymod_bottomlight = newValue.detail.value.toString();
						console.log('Mymod下光源:', this.Mymod_bottomlight);
					}
				}

				// 执行完成后清除定时器记录
				delete this.timers[lightType];
			}, 1500);
		},
		//大路灯开关
		async open_light() {
			if(this.error_show==true){
				return
			}
			if (this.switch_type == false) {
				await this.setControlParam('switch', 1);
			} else {
				await this.setControlParam('switch', 0);
			}
		},
		// 我的模式样式切换
		changeBox(index) {
			this.List.forEach((item, i) => {
				if (i === index) {
					item.active = !item.active;
				} else {
					item.active = false;
				}
			});
		},
		// 情景模式样式切换
		async changeBox_Scene(index) {
			for (let i = 0; i < this.List_Scene.length; i++) {
				const item = this.List_Scene[i];
				if (i === index && item.id != '') {
					item.active = !item.active;
					// 发送情景模式上下光源
					await this.setControlParam('switch', '1');
					// await this.setControlParam('upperBrightness', item.upperBrightness);
					// await this.setControlParam('lowerBrightness', item.lowerBrightness);
					// await this.setControlParam('ScenarioMode', null, item.id);
					await this.setControlParam('ScenarioMode', item.id, null);
					console.log('情景模式', item.id);
				} else {
					item.active = false;
				}
			}
		},
		//我的模式设置
		open_addMode(item) {
			this.Mymod = item;
			this.popup = true;
		},
		//我的模式确定按钮
		add_Mode() {
			this.popup = false;
			// 添加一秒延迟后再执行 createRule
			setTimeout(() => {
				this.createRule(this.Mymod, 'Mymod');
			}, 1500); // 1000毫秒 = 1秒
		},
		//关闭延迟选择框
		closepopup_time(hour, minute) {
			this.$refs.popup_time.close();
			this.DelayList = {};
			this.DelayList.hour = hour;
			this.DelayList.minute = minute;
			console.log('小时:', this.DelayList.hour, '分钟:', this.DelayList.minute);
			// 示例1: 当前时间 2023-10-05 14:30，设置 1小时20分钟后触发
			// const cron1 = generateCronExpression(1, 20);
			this.Delaytime = this.DelayList.hour * 60 + this.DelayList.minute;
		},
		// 开启延迟开关
		async switchChange(e) {
			if (this.Delaytime != 5) {
				this.cron = this.generateCronExpression(this.DelayList.hour, this.DelayList.minute);
			}
			console.log('当前core表达式为:', this.cron);
			//判断当前灯是开还是关
			if (this.checked == false) {
				this.checked = !this.checked;
				if (this.switch_type) {
					//当前灯是开着的
					await this.setControlParam('Delayswitch', '1');
					console.log('延迟关灯启动', e.detail.value);
					this.createTimingTask('0');
				} else {
					//当前灯是关着的
					await this.setControlParam('Delayswitch', '0');
					console.log('延迟开灯启动', e.detail.value);
					this.createTimingTask('1');
				}
			}
		},
		//跳转定时页面
		Go_timing() {
			uni.navigateTo({
				url: '/pages/timing/timing' // 跳转到页面 B
			});
		},
		//获取当前url
		GetUrl() {
			this.currentUrl = window.location.href;
			console.log('获取当前url', this.currentUrl);
			// Hejia.getUrlParam(this.currentUrl, 'deviceId');
			// 创建 URL 对象
			const url = new URL(this.currentUrl);
			// 使用 URLSearchParams 提取查询参数
			const params = new URLSearchParams(url.search);
			// 获取 deviceId 参数的值
			this.deviceId = params.get('deviceId');
			// 打印 deviceId 的值
			console.log('deviceId:', this.deviceId);

			// this.currentUrl = window.location.href;
			// console.log('获取当前url', this.currentUrl);

			// // 创建 URL 对象
			// const url = new URL(this.currentUrl);

			// // 获取哈希部分（# 后面的部分）
			// const hashParams = new URLSearchParams(url.hash.substring(2)); // 去掉 '#/'

			// // 获取 deviceId 参数的值
			// this.deviceId = hashParams.get('deviceId');
			// console.log('deviceId:', this.deviceId);

			let pollingInterval = null; // 定义轮询变量
			// 启动轮询
			this.pollGetDeviceInfo(this.deviceId); // 传入设备ID，开始每五秒调用一次
		},
		pollGetDeviceInfo(deviceId) {
			// 使用 setInterval 每隔 5 秒调用一次 getDeviceInfo
			// this.pollingInterval = setInterval(() => {
				console.log(`页面初次加载,正在调用getDeviceInfo获取设备信息，设备ID: ${deviceId}`);
				this.getDeviceInfo(deviceId);
			// }, 5000); // 每 5 秒调用一次
		},
		//获取设备详细信息,connected字段可确定设备最准确的连接状态
		getDeviceInfo(deviceId) {
			Hejia.getDeviceInfo(
				{ deviceId: deviceId },
				(obj) => {
					console.log('获取设备详细信息:', obj.device.id, obj);
					console.log('获取设备在线离线状态:', obj.device.connected);
					if(obj.device.connected==true){
						this.error_show = false
					}else{
						this.error_show = true
					}
					console.log('当前error_show', this.error_show);
				},
				(msg, obj) => {
					console.log('获取设备详细信息失败:', msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
			this.getCurrentParam();
			// this.getUserRuleList(deviceId);
		},
		//获取当前设备参数
		getCurrentParam() {
			Hejia.getCurrentParam(
				{ paramName: ['switch', 'upperBrightness', 'lowerBrightness', 'ScenarioMode', 'Delayswitch'] },
				(device) => {
					// device - Object => device object.
					console.log('获取当前设备参数成功:', device.id, device);
					device.parameters.forEach((item) => {
						if (item.name == 'switch') {
							console.log('当前开关状态:', item.value);
							if (item.value == '1') {
								this.switch_type = true;
							} else {
								// this.checked=false
								this.switch_type = false;
							}
						} else if (item.name == 'Delayswitch') {
							// console.log('当前延迟开关状态:', item.value);
							if (item.value == '1') {
								this.Delayswitch = true;
							} else {
								this.Delayswitch = false;
							}
							// 判断当前延迟按钮
							if (this.Delayswitch == this.switch_type) {
								this.checked = true;
								// console.log('延迟按钮为开启');
							} else {
								this.checked = false;
								// console.log('延迟按钮为关闭');
							}
						} else if (item.name == 'upperBrightness') {
							this.lightsource_top = item.value;
							console.log('当前上光源亮度:', item.value);
						} else if (item.name == 'lowerBrightness') {
							this.lightsource_bottom = item.value;
							console.log('当前下光源亮度:', item.value);
						}
					});
				},
				(msg, obj) => {
					// msg - String => error message
					// obj – Object => { resultCode:!0, resultCodeMessage: string }
					console.log('获取当前设备参数失败:', msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		//获取规则要素
		getRuleElements() {
			// Hejia.getRuleElements(
			// 	(obj) => {
			// 		console.log('获取规则要素成功:', obj);
			// 	},
			// 	(msg, obj) => {
			// 		console.log('获取规则要素失败', obj.resultCode + obj.resultCodeMessage);
			// 	}
			// );
			Hejia.getRuleElements(
				function (obj) {
					// 获取当前时间
					const currentTime = new Date().toLocaleString();
					console.log(`[${currentTime}] 获取规则要素成功:`, obj);
				},
				function (msg, obj) {
					// 获取当前时间
					const currentTime = new Date().toLocaleString();
					console.log(`[${currentTime}] 获取规则要素失败:`, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		//获取设备当前规则
		getUserRuleList(deviceId) {
			Hejia.getUserRuleList(
				{ deviceId: deviceId },
				(obj) => {
					console.log('获取设备当前规则成功:', obj);
				},
				(msg, obj) => {
					console.log('获取设备当前规则失败:', msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		//创建设备规则
		createRule(item, type) {
			let name = item.title;
			let ruleId = item.id;

			const generateRandomID = () => {
				return Math.floor(100 + Math.random() * 900); // 生成100到999之间的随机整数
			};
			if (type == 'Mymod') {
				console.log('当前设置自定义模式上光源:', this.Mymod_toplight);
				console.log('当前设置自定义模式下光源:', this.Mymod_bottomlight);
				Hejia.createRule(
					{
						rule: {
							id: ruleId,
							name: name,
							status: 2,
							timeZone: 'Asia/Shanghai',
							hidden: false,
							default: false, //是否为默认规则
							// 规则触发条件
							trigger: {
								id: generateRandomID(),
								//此触发条件所需要的参数列表
								parameter: [
									{
										name: 'upperBrightness',
										value: this.Mymod_toplight.toString()
									},
									{
										name: 'lowerBrightness',
										value: this.Mymod_bottomlight.toString()
									}
								]
							},
							// 表示规则执行允许或者禁止的时间段
							calendar: [
								{
									include: false,
									startTime: 0,
									endTime: 86399,
									daysOfWeek: 127
								}
							],
							// 请将所有state置于and的数组的state数组内，表示所有条件都要满足
							states: {
								and: [
									{
										state: [
											{
												id: generateRandomID(),
												parameter: [
													{
														name: 'upperBrightness',
														value: this.Mymod_toplight.toString()
													}
												]
											},
											{
												id: generateRandomID(),
												parameter: [
													{
														name: 'lowerBrightness',
														value: this.Mymod_bottomlight.toString()
													}
												]
											}
										]
									}
								]
							},
							actions: {
								action: [
									{
										id: generateRandomID(),
										parameter: [
											{
												name: 'upperBrightness',
												value: this.Mymod_toplight.toString()
											},
											{
												name: 'lowerBrightness',
												value: this.Mymod_bottomlight.toString()
											}
										]
									}
								]
							}
						}
					},
					(obj) => {
						console.log('创建规则成功:', obj);
						const currentTime = new Date().toLocaleString();
						console.log(`[${currentTime}] 创建规则成功:`, obj);
					},
					(msg, obj) => {
						const currentTime = new Date().toLocaleString();
						console.log(`[${currentTime}] 创建规则失败:`, obj);
						console.log('创建规则失败:', msg, obj.resultCode + obj.resultCodeMessage);
					}
				);
			} else {
			}
		},
		//更新规则
		updateRule() {},
		//删除设备规则
		deleteRule(ruleId) {
			Hejia.deleteRule(
				{ ruleId: ruleId },
				() => {
					console.log('删除成功');
				},
				(msg, obj) => {
					console.log('删除失败', msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		//创建定时任务的接口
		createTimingTask(type) {
			console.log('正在创建定时任务:', type);
			const params = {
				name: 'TimingTask',
				deviceId: this.deviceId,
				schedule: this.cron,
				parameters: [{ name: 'switch', value: type }]
			};
			Hejia.createTimingTask(
				params,
				(obj) => {
					console.log(`[${currentTime}] 创建定时任务成功:`, JSON.stringify(obj));
				},
				(msg, obj) => {
					console.log(`[${currentTime}] 创建定时任务失败:`, msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		//发送管控命令参数(softVersion为参数对象,content为参数值)
		setControlParam(softVersion, content = null, index = null) {
			return new Promise((resolve, reject) => {
				Hejia.setControlParam(
					{
						parameters: {
							param: [
								{
									name: softVersion,
									content: content,
									index: index // 如果传入了index，它会在这里使用
								}
							]
						}
					},
					() => {
						// success, no response
						console.log('发送管控命令参数成功:', softVersion, content, index);
						// 管控命令发送成功后实时更新状态
						if (softVersion == 'upperBrightness') {
							this.lightsource_top = content;
							for (let i = 0; i < this.List_Scene.length; i++) {
								const item = this.List_Scene[i];
								item.active = false;
							}
						} else if (softVersion == 'lowerBrightness') {
							this.lightsource_bottom = content;
							for (let i = 0; i < this.List_Scene.length; i++) {
								const item = this.List_Scene[i];
								item.active = false;
							}
						} else if (softVersion == 'switch') {
							if (content == '1') {
								this.switch_type = true;
							} else {
								this.switch_type = false;
							}
						} else if (softVersion == 'ScenarioMode') {
						}
						resolve(); // 操作完成，触发 resolve
					},
					(msg, obj) => {
						console.log('发送管控命令参数失败:', softVersion, msg, obj.resultCode + obj.resultCodeMessage);
						reject(new Error('管控命令发送失败')); // 出现错误时触发 reject
					}
				);
			});
		},

		// model提示
		model(title, type) {
			this.tiptitle = title;
			this.modeltype = type;
			this.$nextTick(() => {
				// 确保子组件已渲染完成
				this.$refs.showtip.open();
			});
			// this.model('设置成功','success')
			// this.model('设置失败','error')
			// this.model('请重新设置','cancel')
		},
		//Core表达式
		generateCronExpression(delayHours, delayMinutes) {
			// 参数校验
			if (delayHours < 0 || delayHours > 23 || delayMinutes < 0 || delayMinutes > 59) {
				throw new Error('参数错误：小时范围0-23，分钟范围0-59');
			}

			// 计算总延迟时间（毫秒）
			const totalDelayMs = delayHours * 60 * 60 * 1000 + delayMinutes * 60 * 1000;

			// 计算目标时间
			const now = new Date();
			const targetTime = new Date(now.getTime() + totalDelayMs);

			// 提取时间组件（自动处理跨天/跨月/跨年）
			const targetSeconds = 0; // 固定整点执行
			const targetMinutes = targetTime.getMinutes();
			const targetHours = targetTime.getHours();
			const targetDate = targetTime.getDate();
			const targetMonth = targetTime.getMonth() + 1; // 月份修正
			const targetYear = targetTime.getFullYear();

			// Quartz Cron格式：秒 分 时 日 月 ? 年
			return `${targetSeconds} ${targetMinutes} ${targetHours} ${targetDate} ${targetMonth} ? ${targetYear}`;
		},
		bindChange(e) {
			// if (this.timer) {
			// 	clearTimeout(this.timer);
			// }
			// // 设置 1.5 秒后打印 score
			// this.timer = setTimeout(() => {
			// 	console.log('数据发生变化时触发', e);
			// }, 1500);
		},
		//检查网络状态（仅支持检查本地网关配网方式的网络环境是否符合Andlink要求，无法作用于云网关配网方式）
		checkIfReadyForAndlink() {
			Hejia.checkIfReadyForAndlink(
				(msg) => {
					console.log('检查网络状态', msg);
				},
				(msg, obj) => {
					console.log('检查网络状态失败', msg, obj.resultCode + obj.resultCodeMessage);
				}
			);
		},
		error_bt() {
			// uni.navigateTo({
			// 	url: '/pages/error/error'
			// });
			this.go_error=true
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep .uni-slider-handle-wrapper {
	height: 7px;
}
::v-deep .uni-switch-input {
	height: 22px;
	width: 38px;
}
::v-deep .uni-switch-input:after {
	top: -2px;
	width: 22px;
	height: 22px;
	box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.3);
}
::v-deep .uni-switch-input:before {
	height: 22px;
	width: 38px;
}

.color1 {
	background: linear-gradient(to bottom, rgba(48, 132, 242, 0.3) 0%, hsla(214, 80%, 95%, 0.3) 50%, #f2f5f5 100%);
}
.color2 {
	background-color: #e3e4e4;
}
.color3 {
	background-color: #f3f5f5 !important;
}
.content2 {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;

	.header {
		color: rgba(0, 0, 0, 0.8);
		font-size: 25px !important;
		font-weight: 500;
		font-face: PingFang SC;
		padding: 15px;
	}
	.info {
		margin-top: 10px;
		color: rgba(0, 0, 0, 0.8);
		font-size: 18px !important;
		font-face: PingFang SC;
		line-height: 35px;
		padding: 15px;
	}
	.bt{
		width: 315px;
		margin: 80% auto 0;
		 background: linear-gradient(to right, #53ABFE 0%,  #3084F2 100%);
		 color: #fff;
		  font-size: 17px;
		  font-face: PingFangSC-Regular;
		  character: 0px;
		  border-radius: 20px;
	}
}
.content {
	width: 100%;
	height: 100vh;
	align-items: center;
	// background: linear-gradient(to bottom, #3084F2 0%,  #F2F5F5 30%,  #F2F5F5 100%);
	// background: linear-gradient(to bottom,  rgba(48, 132, 242, 0.3) 0%, hsla(214, 80%, 95%, 0.3) 50%, #f2f5f5 100%);
	margin: 0;
	// padding-bottom: 150px;
	overflow: auto;
	/* 遮罩层 */
	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
		z-index: 10;
	}
	.device {
		width: 100%;
		height: 204px;
		display: flex;
		margin-top: 16px;
		.left {
			width: 50%;
			margin-left: 24px;
			.sp1 {
				display: block;
				color: rgba(0, 0, 0, 0.8);
				font-size: 22px;
				font-face: PingFang SC;
				margin-top: 30%;
			}
			.sp2 {
				display: block;
				color: rgba(0, 0, 0, 0.5);
				font-size: 14px;
				font-face: PingFang SC;
				margin-top: 6px;
			}
			.img {
				margin-top: 20px;
				width: 30px;
				height: 30px;
				border-radius: 50%;
				box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
			}
		}
		.right {
			width: 50%;
			.img {
				margin: 50px 0 0 20%;
				width: 35%;
				height: 65%;
			}
		}
	}
	.header {
		// width: 375px;
		width: 100%;
		height: 264px;
		// background: #00d8af;
		position: relative;
		.img1 {
			height: 24px;
			width: 24px;
			margin: 32px 0 0 16px;
			display: inline-block;
		}
		.title {
			position: absolute;
			top: 65%;
			left: 50%;
			transform: translate(-50%, -50%);
			display: inline-block;
			width: 154px;
			height: 24px;
			font-weight: 400;
			font-size: 17px;
			color: #ffffff;
			line-height: 24px;
			text-align: center;
			font-face: PingFangSC-Regular;
		}
		.img2 {
			width: 28px;
			height: 28px;
			position: absolute;
			top: 30px;
			right: 52px;
			bottom: 6px;
		}
		.img3 {
			width: 24px;
			height: 24px;
			position: absolute;
			top: 32px;
			right: 16px;
			bottom: 8px;
		}
	}
	.logo {
		// width: 375px;
		width: 100%;
		height: 226px;
		background: #00d8af;
		position: relative;
		.img {
			display: block;
			width: 140px;
			height: 140px;
			margin: 20px auto 16px;
		}
		.sp {
			display: block;
			width: 56px;
			height: 20px;
			font-size: 14px;
			margin: 0 auto;
			color: #ffffff;
			font-weight: 400;
		}
	}
	.error_box {
		width: 93%;
		height: 68px;
		margin: 16px auto;
		background: #ffffff;
		border-radius: 8px;
		padding-top: 16px;
		position: relative;
		.sp1 {
			margin-left: 11px;
			// font-weight: 600;
			// font-size: 18px;
			text-align: left;
			display: block;
			margin-bottom: 10px;
			color: rgba(0, 0, 0, 0.8);
			font-size: 15px bold;
			font-face: PingFang SC;
		}
		.sp2 {
			margin-left: 11px;
			display: block;
			color: rgba(0, 0, 0, 0.5);
			font-size: 14px;
			font-face: PingFang SC;
			margin-top: 6px;
		}
		.bt {
			position: absolute;
			width: 88px;
			height: 33px;
			font-size: 14px;
			background: linear-gradient(to right, #53abfe 0%, #3084f2 100%);
			color: #fff;
			border-radius: 14px;
			right: 5%;
			top: 30%;
		}
	}
	.lightsource {
		width: 93%;
		height: 128px;
		margin: 16px auto;
		background: #ffffff;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.lightsource_top {
			width: 100%;
			height: 40px;
			margin-top: 1.7vh;
			position: relative;
			.left {
				position: absolute;
				left: 20px;
				width: 15vw;
				height: 22px;
				line-height: 22px;
				color: rgba(0, 0, 0, 0.8);
				font-size: 15px bold;
				font-face: PingFang SC;
				display: inline-block;
			}
			.right {
				position: absolute;
				width: 70vw;
				height: 18px;
				display: inline-block;
				left: 68px;
				top: -10px;
			}
		}
		.lightsource_bottom {
			width: 100%;
			height: 40px;
			margin-top: 1.7vh;
			position: relative;
			.left {
				position: absolute;
				left: 20px;
				width: 15vw;
				height: 22px;
				line-height: 22px;
				color: rgba(0, 0, 0, 0.8);
				font-size: 15px bold;
				font-face: PingFang SC;
				display: inline-block;
			}
			.right {
				position: absolute;
				width: 70vw;
				height: 18px;
				display: inline-block;
				left: 68px;
				top: -10px;
			}
		}
	}

	.Mode {
		width: 93%;
		margin: 0px auto 16px;
		p {
			font-weight: 600;
			font-size: 18px;
			text-align: left;
			display: block;
			margin-bottom: 10px;
		}
		.Mode_info {
			width: 100%;
			height: 122px;
			background: #ffffff;
			border-radius: 8px;
			display: flex;
			justify-content: space-around;

			.box {
				margin-top: 20px;
				width: 60px;
				height: 82px;
				position: relative;
				.img {
					position: absolute;
					width: 48px;
					height: 48px;
					top: 0;
					left: 6px;
				}
				.sp {
					position: absolute;
					bottom: 0;
					width: 60px;
					height: 18px;
					font-weight: 400;
					font-size: 13px;
					text-align: right;
					color: #7f7f7f;
				}
			}
		}
	}
	.Scene_Mode {
		width: 93%;
		margin: 0px auto 16px;
		p {
			// font-weight: 600;
			// font-size: 18px;
			text-align: left;
			display: block;
			margin-bottom: 10px;
			margin-left: 11px;
			color: rgba(0, 0, 0, 0.8);
			font-size: 15px bold;
			font-face: PingFang SC;
		}
		.Scene_Mode_info {
			width: 100%;
			height: 220px;
			background: #ffffff;
			border-radius: 8px;
			display: flex;
			justify-content: space-around;
			flex-wrap: wrap;
			.box {
				margin-top: 20px;
				width: 25%;
				height: 82px;
				position: relative;
				.img {
					position: absolute;
					width: 48px;
					height: 48px;
					top: 0; /* 垂直居中 */
					left: 50%; /* 水平居中 */
					transform: translate(-50%, 0);
				}
				.sp {
					position: absolute;
					bottom: 0;
					width: 100%;
					height: 18px;
					font-weight: 400;
					font-size: 13px;
					text-align: center;
					color: #7f7f7f;
				}
			}
		}
	}
	.Delay {
		width: 93%;
		height: 140px;
		margin: 0px auto 16px;
		background: #ffffff;
		border-radius: 8px;
		position: relative;
		.img {
			position: absolute;
			top: 20px;
			left: 16px;
			width: 48px;
			height: 48px;
		}
		.sp1 {
			display: inline-block;
			position: absolute;
			top: 33px;
			left: 74px;
			font-weight: 400;
			font-size: 16px;
			color: #000000;
		}
		.switch {
			position: absolute;
			top: 32px;
			right: 16px;
			transform: scale(0.6);
		}
		.sp2 {
			display: inline-block;
			position: absolute;
			top: 88px;
			left: 16px;
			font-weight: 400;
			font-size: 16px;
			color: #000000;
		}
		.sp3 {
			display: inline-block;
			position: absolute;
			top: 130px;
			left: 16px;
			font-weight: 400;
			font-size: 16px;
			color: #000000;
		}
		.Delay_exit {
			display: inline-block;
			position: absolute;
			right: 32px;
			top: 89px;
			font-weight: 400;
			font-size: 14px;
			color: #7f7f7f;
		}
	}
	.timing {
		width: 93%;
		height: 88px;
		margin: 0px auto 16px;
		background: #ffffff;
		border-radius: 8px;
		position: relative;
		.img {
			width: 48px;
			height: 48px;
			position: absolute;
			left: 16px;
			top: 20px;
		}
		.sp1 {
			display: inline-block;
			position: absolute;
			top: 33px;
			left: 74px;
			font-weight: 400;
			font-size: 16px;
			color: #000000;
		}
		.right {
			position: absolute;
			top: 36px;
			right: 16px;
			width: 16px;
			height: 16px;
		}
	}
	.popup {
		z-index: 99;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 303px;
		height: 260px;
		background: #ffffff;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
		.popup_header {
			height: 48px;
			text-align: center;
			font-weight: 600;
			font-size: 18px;
			line-height: 48px;
			color: #000000;
		}
		.info {
			height: 130px;
			.lightsource_top {
				width: 100%;
				margin-top: 27px;
				.left {
					margin-left: 16px;
					width: 4.8%; /* 修改为百分比 */
					height: 22px;
					font-weight: 400;
					font-size: 16px;
					color: #000000;
					display: inline-block;
				}
				.right {
					width: 19.3%; /* 修改为百分比 */
					height: 18px;
					display: inline-block;
					margin-left: 16px;
				}
			}
			.lightsource_bottom {
				width: 100%;
				margin-top: 30px;
				.left {
					margin-left: 16px;
					width: 4.8%; /* 修改为百分比 */
					height: 22px;
					font-weight: 400;
					font-size: 16px;
					color: #000000;
					display: inline-block;
				}
				.right {
					width: 19.3%; /* 修改为百分比 */
					height: 18px;
					display: inline-block;
					margin-left: 16px;
				}
			}
		}
		.bt {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			margin-top: 20px;
			.button {
				width: 112px;
				height: 40px;
				border-radius: 20px;
				font-weight: 500;
				font-size: 16px;
				line-height: 40px;
				border: none;
			}

			.gery {
				background: #e6e6e6;
				color: #737373;
			}
			.green {
				background: #00d8af;
				color: #fff;
			}
		}
	}
	.popup_time {
		width: 100%;
		height: 100%;
		background: #ffffff;
		border-radius: 10px 10px 0px 0px;
		overflow: hidden;
	}
}
</style>
